package alexattar.gdxtest.services;

import alexattar.gdxtest.GdxTestGame;
import alexattar.gdxtest.Profile;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.Json;
import com.badlogic.gdx.utils.Base64Coder;

public class ProfileManager {

	private static final String PROFILE_DATA_FILE = ".tyrian/profile-v1.json";
	private Profile profile;
	
	public ProfileManager() {
	}
	
	public Profile retrieveProfile() {
		Gdx.app.log(GdxTestGame.LOG, "Retrieving profile");
		
		if(profile != null) return profile;
		
		FileHandle profileDataFile = Gdx.files.local(PROFILE_DATA_FILE);
		Json json = new Json();
		if(profileDataFile.exists()) {
			try {
				String profileAsText = profileDataFile.readString().trim();
				
				if (profileAsText.matches("^[A-Za-z0-9/+=]+$")) {
					Gdx.app.log(GdxTestGame.LOG, "Persisted profile is Base64 encoded");
					profileAsText = Base64Coder.decodeString(profileAsText);
				}
				
				profile = json.fromJson(Profile.class, profileAsText); 
			} catch(Exception e) {
				Gdx.app.error(GdxTestGame.LOG, "Unable to parse existing profile data file");
				profile = new Profile();
				persist(profile);
			}
		}
		else {
			profile = new Profile();
			persist(profile);
		}
		
		return profile;
	}
	
	protected void persist(Profile profile) {
		Gdx.app.log(GdxTestGame.LOG, "Persisting profile");
		Json json = new Json();
		
		FileHandle profileDataFile = Gdx.files.external(PROFILE_DATA_FILE);
		String profileAsText = json.toJson(profile);
		
		if (!GdxTestGame.DEV_MODE) {
			profileAsText = Base64Coder.encodeString(profileAsText);
		}
		
		profileDataFile.writeString(profileAsText, false);
	}
	
	public void persist() {
		if (profile != null) {
			persist(profile);
		}
	}

}
